import { useRef, useState } from "react";
import { useRouter } from 'next/router'
import classNames from "classnames";
import { auth } from "@/tools/auth";

export default function Login(props) {

    const router = useRouter()

    const usernameRef = useRef(null);
    const passwordRef = useRef(null);


    // valid message has 3 state: blank:0, valid:1, invalid:2
    const [isUsernameValid, setIsUsernameValid] = useState(0);
    const [isPasswordValid, setIsPasswordValid] = useState(0);


    let usernameClasses = classNames('form-control', {
        'is-valid': isUsernameValid === 1,
        'is-invalid': isUsernameValid === 2,
    });;
    let passwordClasses = classNames('form-control', {
        'is-valid': isPasswordValid === 1,
        'is-invalid': isPasswordValid === 2,
    });


    function validateUsername(e) {
        e.preventDefault();
        if (usernameRef.current.value.length >= 4 && usernameRef.current.value.length <= 15) {
            setIsUsernameValid(1);
        } else {
            setIsUsernameValid(2);
        }
    }


    function validatePassword(e) {
        e.preventDefault();
        const regexPassword = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,20}$/;

        if (passwordRef.current.value.match(regexPassword)) {
            setIsPasswordValid(1);
        } else {
            setIsPasswordValid(2);
        }
    }


    function handleLogin(e) {
        e.preventDefault();
        if (isUsernameValid === 1 && isPasswordValid === 1) {
            const username = usernameRef.current.value;
            const password = passwordRef.current.value;
            try {
                auth.login(username, password);
                router.push('/');
            } catch (error) {
                alert("登录失败: " + error);
            }
        }
    }

    return (
        <div className="d-flex justify-content-center mt-5" >
            <form className="col-md-4">
                <div className="mb-3">
                    <label className="form-label">昵称 <span className="small text-muted">长度4-15</span></label>
                    <input type="text" className={usernameClasses} ref={usernameRef} onInput={validateUsername} placeholder="请填写昵称" required />
                    <div className="invalid-feedback">
                        用户名不存在
                    </div>
                </div>
                <div className="mb-3">
                    <label for="password" className="form-label">密码 <span className="small text-muted">包含数字,英文,字符中的两种以上,长度8-20</span></label>
                    <input type="password" className={passwordClasses} ref={passwordRef} onInput={validatePassword} placeholder="请填写密码" required />
                    <div className="invalid-feedback">
                        包含数字,英文,字符中的两种以上,长度8-20
                    </div>
                </div>
                <button type="submit" className="btn btn-primary" onClick={handleLogin}>登录</button>
            </form>
        </div>
    )
};
